package com.boot.learning.springsecurity;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.security.SecurityProperties;
import org.springframework.boot.autoconfigure.security.SecurityProperties.User;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * 引入spring-security配置
 * 
 * @since JDK1.8
 * @author vencano
 * @date 2017年1月8日 下午12:21:22
 */
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

	private static final ObjectMapper MAPPER = new ObjectMapper();
	
	@Override
	protected void configure( HttpSecurity http ) throws Exception{
		http
				/**
				 * 免授权访问接口"/","/home" 其他接口访问，跳转到"/login"
				 */
				.authorizeRequests().antMatchers( "/", "/home", "/v2" )
				.permitAll().anyRequest().authenticated()
				.and()
				/**
				 * 其他访问跳转login登录
				 */
				.formLogin().loginPage( "/login" ).permitAll()
				
				.and().logout().permitAll()
				/**
				 * 禁用csrf:不会认证：CSRF token 报 403
				 */
				.and().csrf().disable();
	}

    /**
     * 设置全局认证用户名、密码
     *
     * @param auth
     * @throws Exception
     * 
     * @author vencano
     * @date 2017年1月8日 下午12:30:34
     */
    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
	        auth
	            .inMemoryAuthentication()
	                .withUser("user").password("password").roles("USER");
	    /**授权管理打印默认用户名密码 */
		if (auth.isConfigured()) {
			return;
		}
		SecurityProperties securityProperties = new SecurityProperties();
		User user = securityProperties.getUser();
		if (user.isDefaultPassword()) {
			System.err.println("\n\nUsing default security password: " + user.getPassword()
			+ "\n");
			System.err.println(MAPPER.writeValueAsString(user));
		}
    }
}